import { Component, Input, OnInit } from '@angular/core';
import { HttpService } from 'src/app/shared/service/http.service';
import { AlertController, ModalController, Platform } from '@ionic/angular';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { ProcessLoginDataService } from 'src/app/shared/service/process-login-data.service';

declare var Fingerprint; // 1.7.0 指纹登录插件
declare var FingerprintAuth; // 1.7.0 安卓端打包兼容用

// TODO 我的 - 设置
@Component({
  selector: 'app-finger-print-auth',
  templateUrl: './finger-print-auth.component.html',
  styleUrls: ['./finger-print-auth.component.scss'],
})


// TODO 指纹登录
export class FingerPrintAuthComponent implements OnInit {
  @Input() tagData;
  // 左上角按钮
  topLeftBtn: any;
  // 右上角按钮
  topRightBtn: any;
  // 中间第一个按钮
  centerFirstBtn: any;
  // 中间第二个按钮
  centerSecondBtn: any;
  secretKey: any;
  enKey: any;
  // 默认提示
  errorMsgRetry = "指纹验证不通过，请稍后再试";
  showCenterFirstBtnLabel = true;
  constructor(
    private modalCtrl: ModalController,
    private alertController: AlertController,
    private http: HttpService,
    private appGlobalService: AppGlobalService,
    private processLoginData: ProcessLoginDataService,
    private pageModalService: PageModalService
  ) { }

  ngOnInit() {
    if (this.tagData && this.tagData.data && this.tagData.data.buttonLink) {
      this.tagData.data.buttonLink.forEach(element => {
        if (element.submit && element.submit.content.type === 'topLeftBtn') {
          this.topLeftBtn = element;
          // tslint:disable-next-line:no-string-literal
        } else if (element.link && element.link['params']['type'] === 'topRightBtn') {
          this.topRightBtn = element;
        } else if (element.submit && element.submit.content.type === 'centerFirstBtn') {
          this.centerFirstBtn = element;
          // tslint:disable-next-line:no-string-literal
        } else if (element.link && element.link['params']['type'] === 'centerSecondBtn') {
          this.centerSecondBtn = element;
        }
      });
      this.secretKey = this.centerFirstBtn.submit.content.key;

      if (localStorage.getItem('fingerPrintSubmitMobile') !== null) {
        const prefix = localStorage.getItem('fingerPrintSubmitMobile').substring(0, 3);
        const lastNumber = localStorage.getItem('fingerPrintSubmitMobile').substring(7, 11);
        this.tagData.data.data.mobile = prefix + '****' + lastNumber;
      }
    }
    // 检测是否第一次安装
    if (localStorage.getItem('showCenterFirstBtnLabel') !== null && localStorage.getItem('showCenterFirstBtnLabel') === 'false') {
      this.showCenterFirstBtnLabel = false;
      setTimeout(() => {
        this.openModalAndShowFingerPrint(this.centerFirstBtn);
      }, 200);
    }
  }

  openModalAndShowFingerPrint(btn) {
    try {
      // this.presentAlertWithErrorMsgBtn('test');
      // 指纹可用并且已经开启指纹登录
      // TODO enableFingerPrint 为 -1 不校验指纹或者指纹校验失败
      // TODO enableFingerPrint 为 null  第一次弹窗
      // TODO enableFingerPrint 为 1  指纹验证通过 并且开启
      // TODO enableFingerPrint 为 2  已经开启过然后正常退出到首页第二次指纹登录时弹出
      if (localStorage.getItem('enableFingerPrint') !== null && localStorage.getItem('enableFingerPrint') === '2') {
        this.presentAlertAuth(btn);
      } else {
        this.presentAlertWithMsgBtn(btn);
      }
    } catch (error) {

    }
  }

  async closeModal(result?) {
    const modal = await this.modalCtrl.getTop();
    if (modal !== undefined) {
      modal.dismiss({ data: result });
    }
  }

  goPage(link, event?) {
    if (event !== undefined) {
      event.stopPropagation();
    }
    if (link && link.params && link.params.closeModalAfterShow) {
      this.closeModal(link);
    }
    this.pageModalService.openPage(link);

  }

  async presentAlertAuth(submit) {
    // 指纹验证成功之后跳转首页。
    if (localStorage.getItem('platform') === 'ios') {  // ios
      if ((typeof Fingerprint) !== 'undefined') {
        Fingerprint.show({
          description: " ",
          disableBackup: true, // always disabled on Android
        }, (successResp) => {
          localStorage.setItem('enableFingerPrint', '1');
          this.appGlobalService.showToast('指纹校验通过', 1500, 'middle');
          this.fingPrintSubmit();
        }, (errorResp) => {
          console.log('errorobj=', JSON.stringify(errorResp));
          // this.presentAlertWithErrorMsgBtn(JSON.stringify(errorResp));
        });
      }
    } else if (localStorage.getItem('platform') === 'android') { // android
      FingerprintAuth.encrypt({
        clientId: 'clientId',
        username: 'username',
        password: 'password',
        token: 'token',
        description: '',
        disableBackup: true, // always disabled on Android
      }, (successResp) => {
        localStorage.setItem('enableFingerPrint', '1');
        this.appGlobalService.showToast('指纹校验通过', 1500, 'middle');
        this.fingPrintSubmit();
      }, (errorResp) => {
        console.log('errorobj=', JSON.stringify(errorResp));
        // this.presentAlertWithErrorMsgBtn(JSON.stringify(errorResp));
      });
    } else { // 项目预览

    }
    const that = this;
    const alert = await this.alertController.create({
      cssClass: 'customAlert',
      // tslint:disable-next-line:max-line-length
      message: "<img class='fingerPrintIcon' src='assets/fw/fingerPrint.png' ><strong>请验证指纹</strong>",
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "laijian",
          handler: () => {
            // localStorage.setItem('enableFingerPrint', '-1');
            this.closeModal({ success: false });
            // this.fingPrintSubmit();
          }
        }
      ]
    });
    await alert.present();
  }

  fingPrintSubmit() {
    const loginSubmitId = this.appGlobalService.fingerPrintSubmitId;
    let loginSubmitKey = '';
    if (localStorage.getItem('globalSubmitKey') !== null) {
      loginSubmitKey = localStorage.getItem('globalSubmitKey');
    }
    const loginSubmitMobile =
      localStorage.getItem('fingerPrintSubmitMobile') ? localStorage.getItem('fingerPrintSubmitMobile') : '';
    const param = {
      content: {},
      id: loginSubmitId,
      sessionId: localStorage.getItem('sessionId')
    };
    if (this.appGlobalService.fingerPrintParams !== undefined) {
      const contentParams = {};
      if (this.appGlobalService.fingerPrintParams.length > 0) {
        this.appGlobalService.fingerPrintParams.forEach(element => {
          contentParams[element.name] = element.value;
        });
      }
      // tslint:disable-next-line:no-string-literal
      contentParams['key'] = loginSubmitKey;
      // tslint:disable-next-line:no-string-literal
      contentParams['account'] = loginSubmitMobile;
      // tslint:disable-next-line:no-string-literal
      param['content'] = contentParams;
    } else {
      // tslint:disable-next-line:no-string-literal
      param['content'] = { key: loginSubmitKey, account: loginSubmitMobile };
    }
    this.http.post("application/submit", param, async data => {
      if (data.success) {
        this.processLoginData.processLoginData(data, '', param);
      } else {
        this.appGlobalService.showToast(data.message, 3000, "top");
      }
      const alert = await this.alertController.getTop();
      if (alert) {
        alert.dismiss();
      }
      this.closeModal({ success: false });
    });

  }

  async presentAlertWithMsgBtn(submit) {
    const that = this;
    const alert = await this.alertController.create({

      cssClass: 'customAlert',
      // tslint:disable-next-line:max-line-length
      message: "<img class='fingerPrintIcon' src='assets/fw/fingerPrint.png' ><strong>请验证指纹</strong>",
      buttons: [
        {
          text: "暂不开启",
          role: "cancel",
          cssClass: "secondary",
          handler: () => {
            localStorage.setItem('enableFingerPrint', '-1');
            if (!this.showCenterFirstBtnLabel) {
              this.closeModal({ success: false });
            }
          }
        },
        {
          text: '立即开启',
          handler: () => {
            // 弹出指纹登录弹窗并校验
            if (localStorage.getItem('platform') === 'ios') { // ios
              Fingerprint.show({
                description: " ",
                disableBackup: true, // always disabled on Android
              }, (successResp) => {
                localStorage.setItem('enableFingerPrint', '1');
                this.appGlobalService.showToast('指纹校验通过', 1500, 'middle');
                // todo 提交submit 无需使用key直接使用json返回的即可。
                const params = {
                  content: this.centerFirstBtn.submit.content,
                  id: this.centerFirstBtn.submit.id,
                  sessionId: localStorage.getItem('sessionId')
                };
                // this.centerFirstBtn.submit.content.key = successResp;
                if (this.centerFirstBtn.submit.content.key !== undefined) {
                  this.enKey = this.appGlobalService.encryptDes(this.secretKey);
                  // tslint:disable-next-line:no-string-literal
                  params.content['key'] = this.enKey;
                  localStorage.setItem('globalSubmitKey', this.enKey);
                }

                this.http.post('application/submit', params, res => {
                  if (res.success) {
                    this.appGlobalService.showToast(res.message, 1500, 'middle');
                  } else {
                    this.appGlobalService.showToast(res.message, 1500, 'middle');
                  }
                  this.closeModal(res);
                });
              }, (errorResp) => {
                // this.appGlobalService.showToast(errorResp, 1500, 'middle');
                console.log('errorobj=', errorResp);
                // this.presentAlertWithErrorMsgBtn(this.errorMsgRetry);
              });
            } else if (localStorage.getItem('platform') === 'android') { // android

              FingerprintAuth.encrypt({
                clientId: 'clientId',
                username: 'username',
                password: 'password',
                token: 'token',
                description: " ",
                disableBackup: true, // always disabled on Android
              }, (successResp) => {
                localStorage.setItem('enableFingerPrint', '1');
                this.appGlobalService.showToast('指纹校验通过', 1500, 'middle');
                // todo 提交submit 无需使用key直接使用json返回的即可。
                const params = {
                  content: this.centerFirstBtn.submit.content,
                  id: this.centerFirstBtn.submit.id,
                  sessionId: localStorage.getItem('sessionId')
                };
                // this.centerFirstBtn.submit.content.key = successResp;
                if (this.centerFirstBtn.submit.content.key !== undefined) {
                  this.enKey = this.appGlobalService.encryptDes(this.secretKey);
                  // tslint:disable-next-line:no-string-literal
                  params.content['key'] = this.enKey;
                  localStorage.setItem('globalSubmitKey', this.enKey);
                }

                this.http.post('application/submit', params, res => {
                  if (res.success) {
                    this.appGlobalService.showToast(res.message, 1500, 'middle');
                  } else {
                    this.appGlobalService.showToast(res.message, 1500, 'middle');
                  }
                  this.closeModal(res);
                });
              }, (errorResp) => {
                // this.appGlobalService.showToast(errorResp, 1500, 'middle');
                console.log('errorobj=', errorResp);
                // this.presentAlertWithErrorMsgBtn(this.errorMsgRetry);
              });
            } else { // 项目预览
              this.closeModal('');
            }

          }
        }
      ]
    });
    await alert.present();
  }


  async presentAlertWithErrorMsgBtn(msg) {
    const that = this;
    const alert = await this.alertController.create({
      cssClass: 'customAlert',
      message: "<img class='fingerPrintIcon' src='assets/fw/fingerPrint.png' ><strong>" + msg + "</strong>",
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "laijian"
        }]
    });
    await alert.present();
  }
}
